package com.bytic.miaosha.service.impl;

import com.bytic.miaosha.constant.KeyConstant;
import com.bytic.miaosha.exception.GlobalException;
import com.bytic.miaosha.redis.MiaoshaUserKey;
import com.bytic.miaosha.service.RedisService;
import com.bytic.miaosha.utils.UUIDUtils;
import com.bytic.miaosha.vo.LoginVO;
import com.bytic.miaosha.domain.MiaoshaUser;
import com.bytic.miaosha.result.CodeMsg;
import com.bytic.miaosha.mapper.MiaoshaUserMapper;
import com.bytic.miaosha.service.MiaoshaUserService;
import com.bytic.miaosha.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Service
public class MiaoshaUserServiceImpl implements MiaoshaUserService {

    @Autowired
    private MiaoshaUserMapper miaoshaUserMapper;

    @Autowired
    private RedisService redisService;

    /**
     * 添加对象级缓存
     * @param id
     * @return
     */
    @Override
    public MiaoshaUser getById(long id) {
        // 取缓存
        MiaoshaUser miaoshaUser = redisService.get(MiaoshaUserKey.id, "" + id, MiaoshaUser.class);
        if (miaoshaUser != null) {
            return miaoshaUser;
        }
        // 取数据库
        miaoshaUser = miaoshaUserMapper.getById(id);
        if (miaoshaUser != null) {
            redisService.set(MiaoshaUserKey.id, "" + id, miaoshaUser);
        }
        return miaoshaUser;
    }

    @Override
    public String login(HttpServletResponse response, LoginVO loginVO) {
        if (loginVO == null) {
            throw new GlobalException(CodeMsg.SERVER_ERROR);
        }
        String mobile = loginVO.getMobile();
        String password = loginVO.getPassword();
        // 判断用户是否存在
        MiaoshaUser user = getById(Long.parseLong(mobile));
        if (user == null) {
            throw new GlobalException(CodeMsg.MOBILE_NOT_EXIST);
        }
        // 密码校验
        String dbPwd = user.getPassword();
        String dbSalt = user.getSalt();
        String md5Pwd = MD5Utils.formPassToDBPass(password, dbSalt);
        if (!dbPwd.equals(md5Pwd)) {
            throw new GlobalException(CodeMsg.PASSWORD_ERROR);
        }
        // 分布式 session，生成 cookie
        String token = UUIDUtils.uuid();
        addCookie(response, user, token);
        return token;
    }

    private void addCookie(HttpServletResponse response, MiaoshaUser user, String token) {
        redisService.set(MiaoshaUserKey.token, token, user);
        Cookie cookie = new Cookie(KeyConstant.COOKIE_NAME_TOKEN, token);
        cookie.setMaxAge(MiaoshaUserKey.token.expire());
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    /**
     * 根据token获取用户
     * @param token
     * @return
     */
    @Override
    public MiaoshaUser getUserByToken(HttpServletResponse response, String token) {
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        MiaoshaUser miaoshaUser = redisService.get(MiaoshaUserKey.token, token, MiaoshaUser.class);
        // 延长有效时长
        if (miaoshaUser != null) {
            addCookie(response, miaoshaUser, token);
        }
        return miaoshaUser;
    }

    @Override
    public boolean updatePassword(String token, long id, String formPass) {
        MiaoshaUser user = getById(id);
        if (user == null) {
            throw new GlobalException(CodeMsg.MOBILE_NOT_EXIST);
        }
        // 更新数据库
        MiaoshaUser toUpdUser = new MiaoshaUser();
        toUpdUser.setId(user.getId());
        toUpdUser.setPassword(MD5Utils.formPassToDBPass(formPass, user.getSalt()));
        miaoshaUserMapper.update(toUpdUser);
        // 处理缓存
        redisService.delete(MiaoshaUserKey.id, "" + id);
        user.setPassword(toUpdUser.getPassword());
        redisService.set(MiaoshaUserKey.token, token, user);
        return true;
    }
}
